package com.qf.interceptor;

import com.qf.annotation.NoLogin;
import com.qf.constants.CommonConstants;
import com.qf.enums.RedisKeyEnum;
import com.qf.redis.RedisUtil;
import com.qf.util.JwtUtils;
import com.qf.util.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * --- 万物归集  不随你我 ---
 * <p>
 * 快捷短语
 * main ==  public static void main(String[] args);
 * sout ==  System.out.println();
 *
 * @author shuhan
 * @date 2025/6/9
 * @desc
 */
@Component
public class NoLoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 控制层方法封装为handlerMethod对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            Method method = handlerMethod.getMethod();
            // 判断访问的控制层方法是否使用了注解
            boolean ret = method.isAnnotationPresent(NoLogin.class);
            // 如果存在，直接放行
            if (ret) {
                return true;
            }

            // 如果没有注解，判断登录状态
            String token = request.getHeader(CommonConstants.LOGIN_TOKEN);
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("请重新登录");
            }
            //token存在，可以正常解析
            try {
                Claims claims = JwtUtils.parseJWT(token);
                // 将解析的用户id存入ThreadLocal
                UserUtils.setUid((Integer) claims.get("uid"));
            } catch (Exception e) {
                throw new RuntimeException("请重新登录");
            }
            // 判断token是否在黑名单
            String key = RedisKeyEnum.BLACK_LIST.getKey();
            String isBlack = redisUtil.getCacheObject(key);
            System.out.println("isBlack = " + isBlack);
            if(isBlack != null) {
                throw new RuntimeException("登陆已过期,请重新登录");
            }
        }

        return true;
    }
}
